import {
  Form,
  FormItem,
  Input,
  message,
  Radio,
  RadioGroup,
  Select,
  SelectOption,
  Space,
  Upload
} from 'ant-design-vue'
import { defineComponent, PropType, ref, watch } from 'vue'

import { commonApi } from '@/apis'
import type { GetCouponListTypeRes } from '@/apis/commonTypes'
import { SvgIcon } from '@/components'
import UploadFile from '@/components/UploadFile'

import { AwardSettingItem, FROM_DATA } from '../../../types'
import { integerValidator, numberValidator } from '../../../utils'
import styles from './index.module.css'
export default defineComponent({
  name: 'AwardForm',
  props: {
    formData: {
      type: Object as PropType<FROM_DATA>,
      required: true
    },
    couponListOption: {
      type: Array as PropType<GetCouponListTypeRes>,
      required: true
    }
  },
  emits: [
    'addSettting',
    'handleAwardUpload',
    'handleRadioChange',
    'deletePrizeList'
  ],
  setup(props, { emit }) {
    const formRef = ref()
    const fileList = ref([] as any)
    const rulesRef = ref({
      prizeName: [
        {
          required: true,
          message: '请输入奖项名称'
        }
      ],
      prizeType: [
        {
          required: true,
          message: '请选择奖项'
        }
      ],
      prizeInfo: [
        {
          required: true,
          message: '请选择输入/选择奖项内容'
        }
      ],
      prizePicture: [
        {
          required: true,
          message: '请上传奖项图片'
        }
      ],
      winningProbability: [
        {
          required: true,
          validator: numberValidator
        }
      ],
      prizeStock: [{ required: true, validator: integerValidator }]
    } as FormRules)
    watch(
      () => props.formData.prizeList,
      () => {
        props.formData.prizeList.forEach((item, index) => {
          if (item.prizePicture) {
            fileList.value[index] = [
              {
                uid: Math.random().toString().slice(-5),
                url: item.prizePicture
              }
            ]
          }
        })
      },
      {
        immediate: true
      }
    )
    function handleAdd() {
      emit('addSettting', {
        prizeName: '',
        prizeType: '',
        prizeInfo: '',
        prizePicture: '',
        winningProbability: '',
        prizeStock: ''
      } as AwardSettingItem)
    }
    function handleRadioChange(e: Event, index: number) {
      emit('handleRadioChange', index)
    }
    function handleUploadChange(index, file: FileInfo) {
      console.log('upload', file)
      fileList.value[index] = file.fileList
      if (file.file.status === 'done') {
        emit('handleAwardUpload', {
          key: index,
          url: file.fileList[0].response.data
        })
      }
    }
    function handleRemoveUpload(index, file: FileInfo) {
      emit('handleAwardUpload', {
        key: index,
        url: ''
      })
    }
    function close(index: number) {
      emit('deletePrizeList', index)
    }
    function submit() {
      return new Promise<void>((resolve, reject) => {
        formRef.value.validate().then(() => {
          if (
            props.formData.prizeList.some(
              item =>
                (item.prizeType != 3 && !item.prizeInfo) ||
                (item.prizeType == 3 && !item.qrCodeUrl)
            )
          ) {
            reject('请完善奖项内容')
          } else {
            resolve()
          }
        })
      })
    }
    return {
      fileList,
      rulesRef,
      formRef,
      submit,
      handleAdd,
      handleRadioChange,
      handleUploadChange,
      handleRemoveUpload,
      close
    }
  },
  render() {
    const renderItem = (item, index) => (
      <div class={styles.formwrap}>
        {index > 0 ? (
          <SvgIcon
            name="close"
            class={styles.close}
            onClick={() => this.close(index)}
          />
        ) : null}
        <FormItem
          label="奖项名称"
          name={['prizeList', index, 'prizeName']}
          rules={this.rulesRef.prizeName}
        >
          <Input v-model:value={item.prizeName} placeholder="请输入奖项名称" />
        </FormItem>
        <FormItem
          label="奖项"
          name={['prizeList', index, 'prizeType']}
          rules={this.rulesRef.prizeType}
        >
          <RadioGroup
            v-model:value={item.prizeType}
            onChange={e => this.handleRadioChange(e, index)}
          >
            <Radio value={0} style={{ display: 'block' }}>
              积分
              {item.prizeType === 0 ? (
                <Input
                  placeholder="请输入积分"
                  v-model:value={item.prizeInfo}
                  class={styles.radioInput}
                />
              ) : null}
            </Radio>
            <Radio value={1} style={{ display: 'block' }}>
              翻牌次数
              {item.prizeType === 1 ? (
                <Input
                  v-model:value={item.prizeInfo}
                  placeholder="请输入翻牌次数"
                  class={styles.radioInput}
                />
              ) : null}
            </Radio>
            <Radio value={2} style={{ display: 'block' }}>
              卡卷
            </Radio>
            {item.prizeType === 2 ? (
              <Select
                v-model:value={item.prizeInfo}
                placeholder="请选择"
                class={styles.radioInput}
                style={{
                  marginLeft: '24px'
                }}
              >
                {this.couponListOption.map(v => (
                  <SelectOption value={v.id}>{v.name}</SelectOption>
                ))}
              </Select>
            ) : null}
            <Radio value={3} style={{ display: 'block' }}>
              自定义
            </Radio>
            {item.prizeType === 3 ? (
              <UploadFile v-model:urls={item.qrCodeUrl}>二维码图</UploadFile>
            ) : null}
          </RadioGroup>
        </FormItem>
        <FormItem
          label="奖项图片"
          name={['prizeList', index, 'prizePicture']}
          rules={this.rulesRef.prizePicture}
        >
          <Upload
            listType="picture-card"
            fileList={this.fileList[index]}
            action={commonApi.uploadFileUrl}
            onChange={(args: FileInfo) => this.handleUploadChange(index, args)}
            remove={args => this.handleRemoveUpload(index, args)}
            showUploadList={{
              showPreviewIcon: false,
              showRemoveIcon: true
            }}
          >
            {!item.prizePicture ? (
              <div>
                <SvgIcon name="plus" />
                <div>从图库中选择</div>
              </div>
            ) : null}
          </Upload>
          <span class={styles.tips}>建议尺寸：366*274</span>
        </FormItem>
        <FormItem
          label="中奖概率"
          name={['prizeList', index, 'winningProbability']}
          rules={this.rulesRef.winningProbability}
        >
          <Input
            v-model:value={item.winningProbability}
            v-slots={{
              suffix: () => <span>‱</span>
            }}
          />
        </FormItem>
        <FormItem
          label="库存"
          name={['prizeList', index, 'prizeStock']}
          rules={this.rulesRef.prizeStock}
        >
          <Input v-model:value={item.prizeStock} />
        </FormItem>
      </div>
    )
    return (
      <div class={styles.wrap}>
        <Form
          ref="formRef"
          model={this.formData}
          style={{ display: 'flex', flexWrap: 'wrap' }}
        >
          {this.formData.prizeList.map(renderItem)}
          {this.formData.prizeList.length < 9 ? (
            <div class={styles.addBtns} onClick={this.handleAdd}>
              <SvgIcon name="plus" class={styles.addPlus} />
              <div>添加奖项</div>
            </div>
          ) : null}
        </Form>
      </div>
    )
  }
})
